package com.aihongbo.service.t1

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

class LogService : Service() {

    private val TAG = "aihongbo"
    private var serviceStatus = 0 //服务运行状态
    private var dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())

    private val logServiceBinder = LogBinder(this)

    override fun onBind(intent: Intent): IBinder {
        return logServiceBinder
    }

    override fun onCreate() {
        super.onCreate()
        Thread(Runnable {
            while (true) {
                Thread.sleep(1000)
                when (serviceStatus) {
                    1 -> {
                        Log.d(TAG, dateFormat.format(Calendar.getInstance().time))
                    }

                    -1 -> {
                        stopSelf()
                    }
                }
            }
        }).start()
    }

    fun start() {
        serviceStatus = 1
    }

    fun stop() {
        serviceStatus = 0
    }

    fun release() {
        serviceStatus = -1
    }

    class LogBinder(val logService: LogService) : Binder() {
        fun getService(): LogService {
            return logService
        }
    }
}